package com.red.star.wechat.data.utils;

/**
 * @ProjectName: macalline-work-server
 * @Package: com.red.star.macalline.data.utils
 * @Description:
 * @Author: AMGuo
 * @CreateDate: 2018/8/24 上午11:14
 * @Version: 1.0
 */

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.red.star.wechat.data.core.constant.Constant;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;

/**
 * 二维码生成和读的工具类
 */
public class QrCodeCreateUtil {

    /**
     * 生成包含字符串信息的二维码图片
     *
     * @param arrayOutputStream 文件输出流路径
     * @param content           二维码携带信息
     * @param qrCodeSize        二维码图片大小
     * @param imageFormat       二维码的格式
     * @throws WriterException
     * @throws IOException
     */
    public static boolean createQrCode(ByteArrayOutputStream arrayOutputStream, String content, int qrCodeSize, String imageFormat) throws WriterException, IOException {
        //设置二维码纠错级别ＭＡＰ
        Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
        hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);  // 矫错级别
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        //创建比特矩阵(位矩阵)的QR码编码的字符串
        if (CheckUtil.isEmpty(qrCodeSize)) {
            qrCodeSize = 900;
        }
        if (CheckUtil.isEmpty(imageFormat)) {
            imageFormat = Constant.IMAGE_FORMAT_DEFAULT;
        }
        BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap);
        // 使BufferedImage勾画QRCode  (matrixWidth 是行二维码像素点)
        int matrixWidth = byteMatrix.getWidth();
        BufferedImage image = new BufferedImage(matrixWidth - 200, matrixWidth - 200, BufferedImage.TYPE_INT_RGB);
        image.createGraphics();
        Graphics2D graphics = (Graphics2D) image.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, matrixWidth, matrixWidth);
        // 使用比特矩阵画并保存图像
        graphics.setColor(Color.BLACK);
        for (int i = 0; i < matrixWidth; i++) {
            for (int j = 0; j < matrixWidth; j++) {
                if (byteMatrix.get(i, j)) {
                    graphics.fillRect(i - 100, j - 100, 1, 1);
                }
            }
        }
        return ImageIO.write(image, imageFormat, arrayOutputStream);
    }

    /**
     * 创建普通二维码 返回二维码链接
     *
     * @param content
     * @return
     * @throws IOException
     * @throws WriterException
     */
    public static String getQrCodeUrl(String content) throws IOException, WriterException {
        ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
        boolean flag = createQrCode(arrayOutputStream, content, 0, null);
        String fileUrl = "";
        if (flag) {
            fileUrl = FileUtil.uploadFile(UuidUtil.generateShortUuid() + ".png", arrayOutputStream.toByteArray());
        }
        return fileUrl;
    }

    /**
     * 创建普通二维码 返回二维码链接
     *
     * @param content
     * @param qrCodeSize
     * @return
     * @throws IOException
     * @throws WriterException
     */
    public static String getQrCodeUrl(String content, int qrCodeSize) throws IOException, WriterException {
        ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
        boolean flag = createQrCode(arrayOutputStream, content, qrCodeSize, null);
        String fileUrl = "";
        if (flag) {
            fileUrl = FileUtil.uploadFile(UuidUtil.generateShortUuid() + ".png", arrayOutputStream.toByteArray());
        }
        return fileUrl;
    }

    /**
     * 读二维码并输出携带的信息
     */
    public static void readQrCode(InputStream inputStream) throws IOException {
        //从输入流中获取字符串信息
        BufferedImage image = ImageIO.read(inputStream);
        //将图像转换为二进制位图源
        LuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        QRCodeReader reader = new QRCodeReader();
        Result result = null;
        try {
            result = reader.decode(bitmap);
        } catch (ReaderException e) {
            e.printStackTrace();
        }
        System.out.println(result.getText());
    }

    /**
     * 测试代码
     *
     * @throws WriterException
     */
    public static void main(String[] args) throws IOException, WriterException {
        System.err.println(getQrCodeUrl("http://smarketing.chinaredstar.com/H5Make/page.html?task_id=182&tar_foid=ab24517a-9715-26d2-4401-54ecb70bdbe3",1400));
    }

}
